package com.gzdh.tang.modu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.modu.entity.SysUser;
import com.gzdh.tang.modu.entity.TangDevice;
import com.gzdh.tang.modu.mapper.OperaMapper;
import com.gzdh.tang.modu.service.TangDeviceService;
import com.gzdh.tang.modu.vo.SysUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/tang/opera")
public class OperaController {

    @Autowired
    OperaMapper operaMapper;

    @Autowired
    TangDeviceService tangDeviceService;

    @PostMapping("login")
    public Result<Object> login(@RequestParam("user") String user, @RequestParam("pass") String pass) throws Exception {
        Result<Object> result = new Result<>();
        SysUser sysUser = operaMapper.getSysUser(user);

        if (sysUser == null) {
            return Result.error(500, "用户编号或密码错误");
        }
        String password = sysUser.getPasswd().trim();
        byte[] bytes = password.getBytes("GBK");
        byte temp;
        for (int i = 0; i < bytes.length; i++) {
            temp = bytes[i];
            bytes[i] = (byte) ~temp;
        }
        String newPassword = new String(bytes, "GBK");
        if (!newPassword.equals(pass)) {
            return Result.error(500, "用户编号或密码错误");
        }
        TangDevice tangDevice = tangDeviceService.getOne(new QueryWrapper<TangDevice>().lambda().eq(TangDevice::getPosnum, user));

        if (tangDevice == null) {
            return Result.error(500, "该操作员尚未设置操作信息");
        }
        return result;
    }

    @GetMapping("getSysUser")
    public Result<List<SysUserVo>> getSysUser() {
        List<SysUserVo> sysUser = operaMapper.getSysUserVo();
        Result<List<SysUserVo>> result = new Result<>();
        result.setResult(sysUser);
        return result;
    }

    @GetMapping("getUserList")
    public Result<List<Map<String,Object>>> getUserList(@RequestParam("addressNo") String addressNo) {
        List<Map<String,Object>> userList = operaMapper.getUserList(addressNo);
        Result<List<Map<String,Object>>> result = new Result<>();
        result.setResult(userList);
        return result;
    }
}
